/**
 * 简化的标签页管理器 - 基于预渲染HTML
 */

class SimpleTabsManager {
    constructor() {
        this.currentPath = window.location.pathname;
        this.init();
    }
    
    init() {
        this.updateActiveTab();
        this.setupEvents();
    }
    
    updateActiveTab() {
        const tabs = document.querySelectorAll('.chrome-tab[data-url]');
        tabs.forEach(tab => {
            const tabUrl = tab.getAttribute('data-url');
            const isActive = this.isCurrentPage(tabUrl);
            
            if (isActive) {
                tab.classList.add('chrome-tab-current');
            } else {
                tab.classList.remove('chrome-tab-current');
            }
        });
    }
    
    isCurrentPage(url) {
        const currentPath = window.location.pathname;
        
        // 精确匹配
        if (currentPath === url) return true;
        
        // 模糊匹配
        if (url === '/customize' && currentPath.startsWith('/customize')) return true;
        if (url === '/templates' && currentPath.startsWith('/templates')) return true;
        if (url === '/exports' && currentPath.startsWith('/exports')) return true;
        
        return false;
    }
    
    setupEvents() {
        // 标签页点击事件
        document.querySelectorAll('.chrome-tab[data-url]').forEach(tab => {
            tab.addEventListener('click', (e) => {
                const url = tab.getAttribute('data-url');
                if (url && window.location.pathname !== url) {
                    // 保存状态
                    if (window.editorCache) {
                        window.editorCache.saveState();
                    }
                    
                    // 立即更新视觉状态
                    this.setActiveTabByUrl(url);
                    
                    // 跳转页面
                    window.location.href = url;
                }
            });
        });
        
        // 新建标签页按钮
        document.getElementById('globalNewTabBtn')?.addEventListener('click', () => {
            window.open('/intelligent', '_blank');
        });
    }
    
    setActiveTabByUrl(url) {
        document.querySelectorAll('.chrome-tab[data-url]').forEach(tab => {
            const tabUrl = tab.getAttribute('data-url');
            if (tabUrl === url) {
                tab.classList.add('chrome-tab-current');
            } else {
                tab.classList.remove('chrome-tab-current');
            }
        });
    }
}

// 立即初始化，不等待DOM加载完成
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.simpleTabsManager = new SimpleTabsManager();
    });
} else {
    window.simpleTabsManager = new SimpleTabsManager();
}
